// pages/cart/cart.js
import utils from '../../utils/util.js'//工具库
import api from '../../api/api.js'
import common from '../../common.js'
import load from '../templates/loader/loader.js'//载入动画框
Page({

  /**
   * 页面的初始数据
   */
  data: {
    carItem: [],
    empty: {
      isEmpty: false,
      type: "cart",
      text: "购物车空空如也"
    },
    isAllChecked: false,
    total: '0.00',//合计金额
    count: 0,
    startX: 0, //开始坐标
    startY: 0,
    isOrder: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    //初始化载入等待动画
    that.loader = load.loader(that, {
      data: "loader",
      toast: true,
      size: 50,
      borderWidth: 3
    });
    //获取用户信息
    api.getUser({
      done: (user) => {
        that.data.userInfo=user
        that.loadData()
      }
    })
  },
  loadData: function () {
    var that = this
    that.loader.open();
    var jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"userId":' + that.data.userInfo.id + '}}';
    api.getCart({
      method: 'POST',
      data: { REQ_MESSAGE: jsonStr },
      complete: (res) => {
        that.loader.close();//关闭载入动画
        switch (res.statusCode) {
          case 200:
            var data = res.data.rows;
            var empty = that.data.empty
            if (JSON.stringify(data) == "[]" || !data) {
              //列表为空
              empty.isEmpty = true
              data = []
            } else if (data.length > 0) {
              empty.isEmpty = false
              that.data.count = 0
              data.forEach(function (item) {
                item.isChecked = false//是否选中
                item.carts.forEach(function (carts) {
                  var price = carts.unit_price//单价
                  carts.isTouchMove = false;
                  carts.isChecked = false//是否选中
                  carts.price = price//单价
                  // data[i].num = 10.00//数量
                  carts._unit_price = utils.format(price)
                  that.data.count += parseInt(carts.number)
                })
              })
              // that.setData({
              //   carItem: data
              // })
              wx.setStorage({
                key: "carCount",
                data: that.data.count
              })
            }
            that.setData({
              carItem: data,
              empty: empty,
              count: 0,
              isOrder: false,
              isAllChecked: false,
              total: "0.00"
            })
            break;
          case 404:
            wx.showToast(api.status404)
            that.loader.open(api.status404.title);
            break;
          case 500:
            wx.showToast(api.status500)
            that.loader.open(api.status500.title);
            break;
          default:
            wx.showToast(api.statusUnknown)
            that.loader.open(api.statusUnknown.title);
            break;
        }
      },
      fail: (res) => {
        that.loader.open(api.statusFail.title);
      }
    });
  },
  //编辑购物车
  setCart: function (selfData, num) {
    var that = this
    that.loader.open();
    var jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"userId":' + that.data.userInfo.id + ',"goodsId":' + selfData.id + ',"number":' + num + '}}';
    api.setCart({
      method: 'POST',
      data: { REQ_MESSAGE: jsonStr },
      success: (res) => {
        that.loader.close();
      },fail:(res)=>{
        that.loader.close();
      }
    })
  },
  setCartCount: function (e) {
    var that = this
    var selfData = e.currentTarget.dataset;//当前选择
    var carts = that.data.carItem[selfData.p_index].carts[selfData.index]
    var num = carts.number;
    var setTotal = "";
    var index=0;
    that.data.count = 0
    if (parseInt(selfData.type)) {
      num++;
      index=1
    } else {
      num--;
      index=-1
    }
    carts.number = num ? num : 1
    if (num > 0) {
      that.setCart(selfData, index)
    }
    var _count = 0
    that.data.count += parseInt(num)
    that.data.carItem.forEach(function (item) {
      item.carts.forEach(function (carts) {
        _count += parseInt(carts.number)
      })
    })
    wx.setStorage({
      key: "carCount",
      data: _count
    })
    if (carts.isChecked) {
      setTotal = that.setTotal();
      // carts.forEach(function (carts) {
      //   if (carts.isChecked) {
      //     that.data.count += parseInt(carts.number)
      //   }
      // })
      that.setData({
        carItem: that.data.carItem,
        total: setTotal.total,
        count: _count
      })
      return;
    }
    that.setData({
      carItem: that.data.carItem
    })

  },
  /**
   * 选中商品
   */
  selected: function (e) {
    var that = this;
    var selfData = e.currentTarget.dataset//当前项
    var carItem = that.data.carItem;//购物车集合
    var isAllChecked = that.data.isAllChecked;//是否全选
    var setTotal = ""
    var carts = ""
    var isChecked = that.data.isChecked
    //判断全选
    if (selfData.index == -1) {
      isAllChecked = isAllChecked ? false : true
      carItem = that.allChecked(isAllChecked);
    } else {
      //判断是否是父级
      if (selfData.p_index || selfData.p_index >= 0) {
        carts = carItem[selfData.p_index].carts[selfData.index]
        carts.isChecked = carts.isChecked ? false : true
        //判断全局全选单选
        isChecked = that.isChecked()//这个地方存在冗余有待修改
        isAllChecked = isChecked.isAllChecked ? true : false
        that.data.isOrder = isChecked.item.length > 0 ? true : false
      } else {
        carts = carItem[selfData.index]
        carts.isChecked = carts.isChecked ? false : true
        var _array = that.partChecked()
        carItem = _array[0]
        isAllChecked = _array[1]
      }
    }
    isChecked = that.isChecked()//这个地方存在冗余有待修改
    setTotal = that.setTotal();
    that.setData({
      carItem: carItem,
      isAllChecked: isAllChecked,
      total: setTotal.total,
      count: setTotal.count,
      isOrder: isChecked.item.length > 0 ? true : false
    })
  },
  /**
   * 获取已选
   * @return array
   */
  isChecked: function (carts) {
    var that = this
    var json = {}
    json.item = []
    var _i = 0, _j = 0
    that.data.carItem.forEach(function (item) {
      var _k = 0
      item.carts.forEach(function (item) {
        _i++
        if (item.isChecked) {
          _j++
          _k++
          json.item.push(item)
        }
      })
      item.carts.length == _k ? item.isChecked = true : item.isChecked = false//区域全选
    });
    json.isAllChecked = _i == _j ? true : false
    return json;
  },
  /**
   * 获取已选包括旗舰店
   * @return carts
   */
  carItemsChecked: function () {
    var carts = []
    var jsonItem = {}
    var json = {}
    this.data.carItem.forEach(function (item, i) {
      jsonItem = {}
      json = {}
      json.item = []
      var _k = 0
      item.carts.forEach(function (child) {
        if (child.isChecked) {
          _k++
          json.item.push(child)
        }
      })
      if (_k > 0) {
        jsonItem.vendor_name = item.vendor_name
        jsonItem.logo_url = item.logo_url
        jsonItem.vendor_id = item.vendor_id
        jsonItem.child = json.item
        carts.push(jsonItem)
      }
    });
    return carts;
  },
  /**
   * 全选
   * @parame isAllChecked
   * @return array
   */
  allChecked: function (checked) {
    var carItem = this.data.carItem
    carItem.forEach(function (item) {
      item.isChecked = checked
      item.carts.forEach(function (carts) {
        carts.isChecked = checked
      })
    })
    return carItem;
  },
  /**
   * 局部
   * @parame item
   * @return array
   */
  partChecked: function () {
    var array = [], i = 0
    var carItem = this.data.carItem
    carItem.forEach(function (item) {
      item.carts.forEach(function (carts) {
        item.isChecked ? carts.isChecked = true : carts.isChecked = false
      })
      if (item.isChecked) i++
    })
    array[0] = carItem
    array[1] = carItem.length == i ? true : false
    return array;
  },
  /**
   * 计算订单
   */
  setTotal: function () {
    var that = this
    var data = {}
    var total = 0
    var count = 0
    var checkedItem = that.isChecked().item

    for (var i in checkedItem) {
      var _number = parseInt(checkedItem[i].number)
      console.log(checkedItem[i].price)

      total += (checkedItem[i].price * _number)
      count += _number
    }
    data.total = utils.format(total)
    data.count = count
    return data
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    var that = this
    for (var i in that.data.carItem) {
      that.data.carItem[i].carts.forEach(function (v, j) {
        if (v.isTouchMove)//只操作为true的
          v.isTouchMove = false;
      })
    }
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      items: this.data.items
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      selfData = e.currentTarget.dataset,//当前
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标
      //获取滑动角度
      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    if (Math.abs(angle) > 30) return;
    that.data.carItem[selfData.p_index].carts[selfData.index].isTouchMove = touchMoveX > startX ? false : true
    //更新数据
    that.setData({
      carItem: that.data.carItem
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除事件
  delCart: function (e) {
    var that = this
    var selfData = e.currentTarget.dataset
    wx.showModal({
      title: '提示',
      content: '确定删除此商品？',
      confirmColor: "#e30c26",
      success: function (res) {
        if (res.confirm) {
          that.loader.open()
          var jsonStr = '{"REQ_HEAD":{"SIGN":"null"},"REQ_BODY":{"userId":' + that.data.userInfo.id + ',"id":' + selfData.id + '}}'
          api.delCart({
            method: 'POST',
            data: { REQ_MESSAGE: jsonStr },
            complete: (res) => {
              var data = res.data
              that.loader.close()//关闭载入动画
              var toastObj = {}
              switch (res.statusCode) {
                case 200:
                  if (data.REP_BODY.RSPCOD == "000000") {
                    that.data.carItem[selfData.p_index].carts.splice(selfData.index, 1)
                    if (that.data.carItem[selfData.p_index].carts.length <= 0) {
                      that.data.carItem.splice(selfData.p_index, 1)
                    }
                    if (that.data.carItem.length <= 0) {
                      that.data.empty.isEmpty = true
                      that.setData({
                        empty: that.data.empty
                      })
                    }
                    that.setData({
                      carItem: that.data.carItem
                    })
                    wx.showToast({
                      title: '删除成功！',
                      icon: 'success'
                    })
                    var setTotal = that.setTotal();
                    that.setData({
                      total: setTotal.total,
                      count: setTotal.count
                    })
                  } else {
                    wx.showToast(api.statusFail)
                    that.loader.open("删除失败！");
                  }
                  break;
                case 404:
                  wx.showToast(api.status404)
                  break;
                case 500:
                  wx.showToast(api.status500)
                  break;
                default:
                  wx.showToast(api.statusUnknown)
                  break;
              }
            },
            fail: (res) => {
              wx.showToast(api.status500)
            }
          });

        }
      }
    })
  },
  confirmOrder: function () {
    var that = this
    if (that.data.isOrder) {
      var str = JSON.stringify(that.carItemsChecked());
      var encodeStr = encodeURI(encodeURI(str))
      wx.navigateTo({
        url: '/pages/order/confirmOrder/confirmOrder?order=' + encodeStr,
      })
    }
  },
  onShow: function () {
    var that = this
    //购物车计数
    api.getUser({
      done: (user) => {
        that.data.userInfo=user
        that.loadData()
      },
      fail: () => {
        var empty = that.data.empty
        empty.isEmpty = true
        that.setData({
          empty: empty,
          carItem: []
        })
        // wx.navigateTo({
        //   url: '/pages/login/login',
        // });
      }
    })
  }
})